package com.bailian.service;

import com.alibaba.fastjson.JSONObject;
import com.bailian.config.RedisDataSoureceTransaction;
import com.bailian.constant.Constants;
import com.bailian.core.utils.BeanCopyUtils;
import com.bailian.core.utils.GenerateTokenUtil;
import com.bailian.core.utils.MD5Util;
import com.bailian.core.utils.RedisUtil;
import com.bailian.mapper.UserMapper;
import com.bailian.mapper.UserTokenMapper;
import com.bailian.mapper.entity.UserDo;
import com.bailian.mapper.entity.UserTokenDo;
import com.bailian.member.IMemberLoginService;
import com.bailian.member.dto.input.UserLoginInpDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClassName: IMemberService <br/>
 * Description: <br/>
 * date: 2019/9/3 23:53<br/>
 *
 * @author XT<br />
 */
@RestController
public class MemberLoginService extends BaseApiService<JSONObject> implements IMemberLoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserTokenMapper userTokenMapper;

    @Autowired
    private GenerateTokenUtil generateToken;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisDataSoureceTransaction redisDataSoureceTransaction;

    @Override
    public BaseResponse<JSONObject> login(@RequestBody @Validated UserLoginInpDTO userLoginInpDTO) {
        TransactionStatus transactionStatus = null;
        try {
            transactionStatus = redisDataSoureceTransaction.begin();
            String password = MD5Util.MD5(userLoginInpDTO.getPassword());
            UserDo userDo = userMapper.existMobile(userLoginInpDTO.getMobile());
            if (userDo != null) {
                if (userDo.getPassword().equals(password)) {
                    final Long userId = userDo.getUserId();
                    final UserTokenDo userTokenDo = userTokenMapper.selectByUserIdAndLoginType(userId, userLoginInpDTO.getLoginType());
                    if (userTokenDo != null) {
                        final String token = userTokenDo.getToken();
                        redisUtil.delKey(token);
                        userTokenMapper.updateTokenAvailability(userId, userLoginInpDTO.getLoginType());
                    }
                    JSONObject jsonObject = new JSONObject();
                    String tokenKey = new StringBuilder().append(userLoginInpDTO.getLoginType()).append(".").append(Constants.TOKEN_MEMBER).append(".").toString();
                    final String token = generateToken.createToken(tokenKey, userId.toString());
                    jsonObject.put("token", token);
                    final UserTokenDo userTokenDo1 = BeanCopyUtils.dtoToDo(userLoginInpDTO, UserTokenDo.class);
                    userTokenDo1.setToken(token);
                    userTokenDo1.setUserId(userId);
                    userTokenMapper.insertUserToken(userTokenDo1);
                    redisDataSoureceTransaction.commit(transactionStatus);
                    return setResultSuccess(jsonObject);
                }
                return setResultError("用户名或密码错误");
            }
            return setResultError("用户尚未注册");
        } catch (Exception e) {
            try {
                redisDataSoureceTransaction.rollback(transactionStatus);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return setResultError("系统错误");
        }

    }
}
